﻿using Elysium.Notifications;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WGM
{
    public partial class PageGames : Page
    {
        public PageGames()
        {
            InitializeComponent();
        }

        ClassSQL ClassSQL = new ClassSQL();

        string filter1;
        string filter2;
        string sql;
        int playing = 0;
        int savemode = 0;

        TimeSpan timespan;
        DateTime starttime;
        DispatcherTimer timer;

        private void page_games_Loaded(object sender, RoutedEventArgs e)
        {
            rectangle_stats.Visibility = Visibility.Hidden;
            label_stats.Visibility = Visibility.Hidden;
            textbox_playtime.Visibility = Visibility.Hidden;
            button_stats.Visibility = Visibility.Hidden;
            label_avgsession.Visibility = Visibility.Hidden;
            textbox_avgsession.Visibility = Visibility.Hidden;
            label_lplay.Visibility = Visibility.Hidden;
            textbox_lplay.Visibility = Visibility.Hidden;
            label_completionstatus.Visibility = Visibility.Hidden;
            textbox_completionstatus.Visibility = Visibility.Hidden;
            label_session.Visibility = Visibility.Hidden;
            textbox_session.Visibility = Visibility.Hidden;

            tabitem_defiance.Visibility = Visibility.Collapsed;
            progressring_defiance.Visibility = Visibility.Hidden;
            webbrowser_defiance.Visibility = Visibility.Hidden;

            string dselection = Properties.Settings.Default.dselection;
            switch (dselection)
            {
                case "AG":
                    filter1 = "IP";
                    filter2 = "CO";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill(this, sql);

                    label_selection.Content = "All Games";
                    break;

                case "IP":
                    filter1 = "UF";
                    filter2 = "AG";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "IP");

                    label_selection.Content = "In Progress Games";
                    break;

                case "UF":
                    filter1 = "US";
                    filter2 = "IP";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "UF");

                    label_selection.Content = "Unfinished Games";
                    break;

                case "US":
                    filter1 = "CO";
                    filter2 = "UF";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "US");

                    label_selection.Content = "Unstarted Games";
                    break;

                case "FAV":
                    filter1 = "IP";
                    filter2 = "CO";

                    sql = "SELECT * FROM gamecentral WHERE favorite='Yes' ORDER BY gamename";
                    ClassSQL.gamesfill(this, sql);

                    label_selection.Content = "Favorite";

                    label_right.Visibility = Visibility.Hidden;
                    label_left.Visibility = Visibility.Hidden;
                    break;
            }

            string editstate = Properties.Settings.Default.editstate;
            if (editstate == "1")
            {
                tab_edit.Visibility = Visibility.Visible;
            }
            else
            {
                tab_edit.Visibility = Visibility.Collapsed;
            }

            string review = Properties.Settings.Default.review;
            if (review == "1")
            {
                tab_review.Visibility = Visibility.Visible;
            }
            else
            {
                tab_review.Visibility = Visibility.Collapsed;
            }

            textbox_search.Focus();

            rectangle_steam.Visibility = Visibility.Hidden;
            label_steam.Visibility = Visibility.Hidden;
            textbox_steam.Visibility = Visibility.Hidden;
            button_steam.Visibility = Visibility.Hidden;
        }

        private void label_left_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            textbox_search.Text = "";
            switch (filter2)
            {
                case "AG":
                    filter1 = "IP";
                    filter2 = "CO";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill(this, sql); ClassSQL.gamesfill(this, sql);

                    label_selection.Content = "All Games";
                    break;

                case "IP":
                    filter1 = "UF";
                    filter2 = "AG";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "IP"); ClassSQL.gamesfill_special(this, sql, "IP");

                    label_selection.Content = "In Progress Games";
                    break;

                case "UF":
                    filter1 = "US";
                    filter2 = "IP";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "UF"); ClassSQL.gamesfill_special(this, sql, "UF");

                    label_selection.Content = "Unfinished Games";
                    break;

                case "US":
                    filter1 = "CO";
                    filter2 = "UF";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "US"); ClassSQL.gamesfill_special(this, sql, "US");

                    label_selection.Content = "Unstarted Games";
                    break;

                case "CO":
                    filter1 = "AG";
                    filter2 = "US";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "CO"); ClassSQL.gamesfill_special(this, sql, "CO");

                    label_selection.Content = "Completed Games";
                    break;
            }
        }

        private void label_right_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            textbox_search.Text = "";
            switch (filter1)
            {
                case "AG":
                    filter1 = "IP";
                    filter2 = "CO";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill(this, sql); ClassSQL.gamesfill(this, sql);

                    label_selection.Content = "All Games";
                    break;

                case "IP":
                    filter1 = "UF";
                    filter2 = "AG";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "IP");

                    label_selection.Content = "In Progress Games";
                    break;

                case "UF":
                    filter1 = "US";
                    filter2 = "IP";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "UF");

                    label_selection.Content = "Unfinished Games";
                    break;

                case "US":
                    filter1 = "CO";
                    filter2 = "UF";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "US");

                    label_selection.Content = "Unstarted Games";
                    break;

                case "CO":
                    filter1 = "AG";
                    filter2 = "US";

                    sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill_special(this, sql, "CO");

                    label_selection.Content = "Completed Games";
                    break;
            }
        }

        private void listbox_gamelist_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            rectangle_stats.Visibility = Visibility.Hidden;
            label_stats.Visibility = Visibility.Hidden;
            textbox_playtime.Visibility = Visibility.Hidden;
            button_stats.Visibility = Visibility.Hidden;
            label_avgsession.Visibility = Visibility.Hidden;
            textbox_avgsession.Visibility = Visibility.Hidden;
            label_lplay.Visibility = Visibility.Hidden;
            textbox_lplay.Visibility = Visibility.Hidden;
            label_session.Visibility = Visibility.Hidden;
            textbox_session.Visibility = Visibility.Hidden;

            tabControl.SelectedIndex = 0;

            ClassSQL.datarefresh(this);
        }

        private void label_gamestart_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (playing == 0)
            {
                label_left.IsEnabled = false;
                label_left.Opacity = 0.25;
                label_right.IsEnabled = false;
                label_right.Opacity = 0.25;
                listbox_gamelist.IsEnabled = false;
                grid_detail.IsEnabled = false;
                gird_review.IsEnabled = false;
                gid_edit.IsEnabled = false;
                textbox_search.IsEnabled = false;
                label_completionstatus.Visibility = Visibility.Visible;
                textbox_completionstatus.Visibility = Visibility.Visible;

                playing = 1;
                label_gamestart.Content = "q";

                string gamename = listbox_gamelist.SelectedItem.ToString();
                string sqlcm = "SELECT * FROM gamecentral WHERE gamename = '" + gamename + "'";
                ClassSQL.gamestart(sqlcm);

                starttime = DateTime.Now;

                timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
                {
                    DateTime stoptime = DateTime.Now;
                    timespan = stoptime - starttime;
                    this.label_gamestart_text.Content = "Session: " + new DateTime(timespan.Ticks).ToString("HH:mm:ss");
                }, this.Dispatcher);
            }
            else
            {
                label_left.IsEnabled = true;
                label_left.Opacity = 1;
                label_right.IsEnabled = true;
                label_right.Opacity = 1;
                listbox_gamelist.IsEnabled = true;
                grid_detail.IsEnabled = true;
                gird_review.IsEnabled = true;
                gid_edit.IsEnabled = true;
                textbox_search.IsEnabled = true;

                playing = 0;
                this.timer.Stop();
                label_gamestart_text.Content = "Launch and Play";
                label_gamestart.Content = "4";

                DateTime stoptime = DateTime.Now;
                TimeSpan timespan = stoptime - starttime;

                DateTime.Now.ToShortDateString();

                string timeplayedpass1 = new DateTime(timespan.Ticks).ToString("HH");
                string timeplayedpass2 = new DateTime(timespan.Ticks).ToString("mm");

                int timeplayedpass1_1 = Convert.ToInt32(timeplayedpass1) * 60;
                int timeplayedpass = timeplayedpass1_1 + Convert.ToInt32(timeplayedpass2);

                string gamename = listbox_gamelist.SelectedItem.ToString();

                int playday = starttime.Day;

                CultureInfo ciCurr = CultureInfo.CurrentCulture;
                int weekNum = ciCurr.Calendar.GetWeekOfYear(starttime, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
                int playweek = weekNum;

                int playmonth = starttime.Month;
                int playyear = starttime.Year;

                string comstat = textbox_completionstatus.Text;

                if (comstat == "")
                {
                    sql = @"INSERT INTO timetrack([gamelink], [sessiontime], [playday], [playweek], [playmonth], [playyear])VALUES('" + gamename + "', '" + timeplayedpass + "', '" + playday + "', '" + playweek + "', '" + playmonth + "', '" + playyear + "')";
                    ClassSQL.gamesupdate(sql);
                }
                else
                {
                    sql = @"INSERT INTO timetrack([gamelink], [sessiontime], [playday], [playweek], [playmonth], [playyear], [completedstatus], [completedtype])VALUES('" + gamename + "', '" + timeplayedpass + "', '" + playday + "', '" + playweek + "', '" + playmonth + "', '" + playyear + "', 'Yes', '" + comstat + "')";
                    ClassSQL.gamesupdate(sql);

                    ClassSQL.gamescomplecal(gamename);
                }

                sql = @"UPDATE gamecentral SET lastplayed='" + DateTime.Now.ToString("D") + "', lastplayedweek='" + playweek.ToString() + "', lastplayedmonth='" + playmonth.ToString() + "' WHERE gamename = '" + gamename + "'";
                ClassSQL.gamesupdate(sql);

                ClassSQL.datarefresh(this);

                label_completionstatus.Visibility = Visibility.Hidden;
                textbox_completionstatus.Visibility = Visibility.Hidden;
                textbox_completionstatus.Text = "";
            }
        }

        private void button_save_Click(object sender, RoutedEventArgs e)
        {
            button_save.Content = "Change Saved";

            Thread displaychange = new Thread(WriteSave);
            displaychange.Start(this);

            string completstate;
            if (checkbox_completed.IsChecked == true)
            {
                completstate = "Yes";
            }
            else
            {
                completstate = "No";
            }

            string gamename = listbox_gamelist.SelectedItem.ToString();
            string description = textbox_descpedit.Text.Replace("'", "");

            sql = @"UPDATE gamecentral SET gametype='" + combobox_type.Text + "', gamecompatibility='" + combobox_comp.Text + "', gamedescription='" + description + "', completed='" + completstate + "' WHERE gamename = '" + gamename + "'";
            ClassSQL.gamesupdate(sql);
            ClassSQL.datarefresh(this);
        }

        private void WriteSave(object obj)
        {
            Thread.Sleep(1000);
            this.Dispatcher.Invoke((Action)(() =>
            {
                button_save.Content = "Save";
            }));
        }

        private void button_cover_Click(object sender, RoutedEventArgs e)
        {
            string gamename = listbox_gamelist.SelectedItem.ToString();

            var dialog = new System.Windows.Forms.OpenFileDialog();
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();

            string imgpath = dialog.FileName;
            if (imgpath != "")
            {
                File.Copy(imgpath, AppDomain.CurrentDomain.BaseDirectory + @"\Gamecover\" + gamename + ".jpg", true);
                ClassSQL.datarefresh(this);
            }
        }

        private void button_exe_Click(object sender, RoutedEventArgs e)
        {
            if (checkbox_steam.IsChecked == true)
            {
                rectangle_steam.Visibility = Visibility.Visible;
                label_steam.Visibility = Visibility.Visible;
                textbox_steam.Visibility = Visibility.Visible;
                button_steam.Visibility = Visibility.Visible;
            }
            else
            {
                var dialog = new System.Windows.Forms.OpenFileDialog();
                System.Windows.Forms.DialogResult result = dialog.ShowDialog();

                if (dialog.FileName != "")
                {
                    string gamename = listbox_gamelist.SelectedItem.ToString();
                    sql = @"UPDATE gamecentral SET pathtogame='" + dialog.FileName + "' WHERE gamename = '" + gamename + "'";
                    ClassSQL.gamesupdate(sql);
                    ClassSQL.datarefresh(this);
                }
            }
        }

        private void button_path_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();

            if (dialog.SelectedPath != "")
            {
                string gamename = listbox_gamelist.SelectedItem.ToString();
                sql = @"UPDATE gamecentral SET savegamepath='" + dialog.SelectedPath + "' WHERE gamename = '" + gamename + "'";
                ClassSQL.gamesupdate(sql);
                ClassSQL.datarefresh(this);
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string gamename = listbox_gamelist.SelectedItem.ToString();
            sql = @"UPDATE gamecentral SET pathtogame='steam://rungameid/" + textbox_steam.Text + "' WHERE gamename = '" + gamename + "'";
            ClassSQL.gamesupdate(sql);

            ClassSQL.datarefresh(this);

            rectangle_steam.Visibility = Visibility.Hidden;
            label_steam.Visibility = Visibility.Hidden;
            textbox_steam.Visibility = Visibility.Hidden;
            button_steam.Visibility = Visibility.Hidden;

            textbox_steam.Text = "";
        }

        private void button_edit_Click(object sender, RoutedEventArgs e)
        {
            if (savemode == 1)
            {
                savemode = 0;
                button_edit.Content = "Edit";
                textbox_note.Visibility = Visibility.Visible;
                textbox_thegood.BorderThickness = new Thickness(0, 0, 0, 0);
                textbox_thebad.BorderThickness = new Thickness(0, 0, 0, 0);
                comboxbox_note.BorderThickness = new Thickness(0, 0, 0, 0);
                textbox_thegood.IsReadOnly = true;
                textbox_thebad.IsReadOnly = true;
                comboxbox_note.IsReadOnly = true;

                textbox_note.Text = comboxbox_note.Text;

                string gamename = listbox_gamelist.SelectedItem.ToString();
                string thegood = textbox_thegood.Text.Replace("'", "");
                string thebad = textbox_thebad.Text.Replace("'", "");

                sql = @"UPDATE gamecentral SET reviewnote='" + comboxbox_note.Text + "', reviewplus='" + thegood + "', reviewmoin='" + thebad + "' WHERE gamename = '" + gamename + "'";
                ClassSQL.gamesupdate(sql);
            }
            else
            {
                savemode = 1;
                button_edit.Content = "Save";
                textbox_note.Visibility = Visibility.Hidden;
                textbox_thegood.BorderThickness = new Thickness(1, 1, 1, 1);
                textbox_thebad.BorderThickness = new Thickness(1, 1, 1, 1);
                comboxbox_note.BorderThickness = new Thickness(1, 1, 1, 1);
                textbox_thegood.IsReadOnly = false;
                textbox_thebad.IsReadOnly = false;
                comboxbox_note.IsReadOnly = false;
            }
        }

        private void textbox_search_KeyUp(object sender, KeyEventArgs e)
        {
            filter1 = "IP";
            filter2 = "CO";
            label_selection.Content = "Search Result";
            label_right.Visibility = Visibility.Hidden;
            label_left.Visibility = Visibility.Hidden;

            if (!Char.IsDigit((char)KeyInterop.VirtualKeyFromKey(e.Key)) & e.Key != Key.Back | e.Key == Key.Enter)
            {
                if (e.Key == Key.RightCtrl | e.Key == Key.LeftCtrl)
                {
                    textbox_search.Text = "";
                    string sql = "SELECT * FROM gamecentral ORDER BY gamename";
                    ClassSQL.gamesfill(this, sql); ClassSQL.gamesfill(this, sql);
                    label_selection.Content = "All Games";
                    label_right.Visibility = Visibility.Visible;
                    label_left.Visibility = Visibility.Visible;
                }
                else
                {
                    string sql = "SELECT * FROM gamecentral WHERE gamename LIKE '%" + textbox_search.Text + "%' ORDER BY gamename";
                    ClassSQL.gamesfill(this, sql); ClassSQL.gamesfill(this, sql);
                }
            }
        }

        private void menuitem_selected0_Click(object sender, RoutedEventArgs e)
        {
            if (playing == 0)
            {
                label_left.IsEnabled = false;
                label_left.Opacity = 0.25;
                label_right.IsEnabled = false;
                label_right.Opacity = 0.25;
                listbox_gamelist.IsEnabled = false;
                grid_detail.IsEnabled = false;
                gird_review.IsEnabled = false;
                gid_edit.IsEnabled = false;
                textbox_search.IsEnabled = false;

                label_completionstatus.Visibility = Visibility.Visible;
                textbox_completionstatus.Visibility = Visibility.Visible;

                playing = 1;
                label_gamestart.Content = "q";

                string gamename = listbox_gamelist.SelectedItem.ToString();
                string sql = "SELECT * FROM gamecentral WHERE gamename = '" + gamename + "'";

                ClassSQL.gamestart(sql);

                starttime = DateTime.Now;

                timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
                {
                    DateTime stoptime = DateTime.Now;
                    timespan = stoptime - starttime;
                    this.label_gamestart_text.Content = "Session: " + new DateTime(timespan.Ticks).ToString("HH:mm:ss");
                }, this.Dispatcher);
            }
            else
            {
                label_left.IsEnabled = true;
                label_left.Opacity = 1;
                label_right.IsEnabled = true;
                label_right.Opacity = 1;
                listbox_gamelist.IsEnabled = true;
                grid_detail.IsEnabled = true;
                gird_review.IsEnabled = true;
                gid_edit.IsEnabled = true;
                textbox_search.IsEnabled = true;

                playing = 0;
                this.timer.Stop();
                label_gamestart_text.Content = "Launch and Play";
                label_gamestart.Content = "4";

                DateTime stoptime = DateTime.Now;
                TimeSpan timespan = stoptime - starttime;

                DateTime.Now.ToShortDateString();

                string timeplayedpass1 = new DateTime(timespan.Ticks).ToString("HH");
                string timeplayedpass2 = new DateTime(timespan.Ticks).ToString("mm");

                int timeplayedpass1_1 = Convert.ToInt32(timeplayedpass1) * 60;
                int timeplayedpass = timeplayedpass1_1 + Convert.ToInt32(timeplayedpass2);

                string gamename = listbox_gamelist.SelectedItem.ToString();

                int playday = starttime.Day;

                CultureInfo ciCurr = CultureInfo.CurrentCulture;
                int weekNum = ciCurr.Calendar.GetWeekOfYear(starttime, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
                int playweek = weekNum;

                int playmonth = starttime.Month;
                int playyear = starttime.Year;

                sql = @"INSERT INTO timetrack([gamelink], [sessiontime], [playday], [playweek], [playmonth], [playyear])VALUES('" + gamename + "', '" + timeplayedpass + "', '" + playday + "', '" + playweek + "', '" + playmonth + "', '" + playyear + "')";
                ClassSQL.gamesupdate(sql);
                sql = @"UPDATE gamecentral SET lastplayed='" + DateTime.Now.ToString("D") + "', lastplayedweek='" + playweek.ToString() + "', lastplayedmonth='" + playmonth.ToString() + "' WHERE gamename = '" + gamename + "'";
                ClassSQL.gamesupdate(sql);

                label_completionstatus.Visibility = Visibility.Visible;
                textbox_completionstatus.Visibility = Visibility.Visible;
                textbox_completionstatus.Text = "";

                ClassSQL.datarefresh(this);
            }
        }

        private void menuitem_selected1_Click(object sender, RoutedEventArgs e)
        {
            string gamename = listbox_gamelist.SelectedItem.ToString();
            int warnning = 0;

            OleDbConnection conn = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\gamesdb.mdb");

            Task backgroundDBTask = Task.Factory.StartNew(() =>
            {
                string sql = "SELECT * FROM gamecentral WHERE gamename = '" + gamename + "'";
                OleDbCommand cmd = new OleDbCommand(sql, conn); conn.Open(); OleDbDataReader reader; reader = cmd.ExecuteReader();

                try
                {
                    while (reader.Read())
                    {
                        if (reader.GetString(2).ToString() != "NOT SET")
                        {
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                NotificationManager.TryPushAsync(gamename, "Backup has been started");
                            }));

                            gamename = reader.GetString(1).ToString();
                            string savepath = reader.GetString(2).ToString();

                            DirectoryCopy(savepath, Properties.Settings.Default.backuppath + @"\" + gamename + @"\", true);
                        }
                        else
                        {
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                NotificationManager.TryPushAsync("WARNING", "This game is not configure for backup");
                                warnning = 1;
                            }));
                        }
                    }
                }
                catch (Exception ex)
                { Console.WriteLine(ex.Message); return; }

                finally
                {
                    reader.Close(); conn.Close();

                    if (warnning == 0)
                    {
                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            NotificationManager.TryPushAsync(gamename, "Backup was completed successfully");
                        }));
                    }
                }
            });
        }

        private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                if (System.IO.Path.Combine(file.Name) != "Thumbs.db")
                {
                    string temppath = System.IO.Path.Combine(destDirName, file.Name);
                    file.CopyTo(temppath, true);
                }
            }

            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = System.IO.Path.Combine(destDirName, subdir.Name);
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }

        private void menuitem_selected3_Click(object sender, RoutedEventArgs e)
        {
            tabControl.SelectedIndex = 1;
        }

        private void menuitem_selected4_Click(object sender, RoutedEventArgs e)
        {
            tabControl.SelectedIndex = 2;
        }

        private void menuitem_selected2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                rectangle_stats.Visibility = Visibility.Visible;
                label_stats.Visibility = Visibility.Visible;
                textbox_playtime.Visibility = Visibility.Visible;
                button_stats.Visibility = Visibility.Visible;
                label_avgsession.Visibility = Visibility.Visible;
                textbox_avgsession.Visibility = Visibility.Visible;
                label_lplay.Visibility = Visibility.Visible;
                textbox_lplay.Visibility = Visibility.Visible;
                label_session.Visibility = Visibility.Visible;
                textbox_session.Visibility = Visibility.Visible;

                string gamename = listbox_gamelist.SelectedItem.ToString();

                DataTable dtResults = new DataTable();
                OleDbConnection conn = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\gamesdb.mdb");
                conn.Open();

                if (conn.State == ConnectionState.Open)
                {
                    OleDbCommand dbCommand = conn.CreateCommand();
                    dbCommand.CommandType = CommandType.Text;
                    dbCommand.CommandText = "SELECT SUM([sessiontime]) AS TOTAL FROM timetrack WHERE gamelink = '" + gamename + "'";

                    OleDbDataReader dbReader = dbCommand.ExecuteReader();

                    if (dbReader.HasRows)
                        dtResults.Load(dbReader);

                    dbReader.Close();
                    conn.Close();
                }

                Int32 timeresult;
                Int32.TryParse(dtResults.Rows[0]["TOTAL"].ToString(), out timeresult);

                textbox_playtime.Text = timeresult + " Minutes / " + timeresult / 60 + " Hours";

                DataTable dtResults_1 = new DataTable();
                conn.Open();

                if (conn.State == ConnectionState.Open)
                {
                    OleDbCommand dbCommand = conn.CreateCommand();
                    dbCommand.CommandType = CommandType.Text;
                    dbCommand.CommandText = "SELECT AVG([sessiontime]) AS AVERAGE FROM timetrack WHERE gamelink = '" + gamename + "'";

                    OleDbDataReader dbReader = dbCommand.ExecuteReader();

                    if (dbReader.HasRows)
                        dtResults_1.Load(dbReader);

                    dbReader.Close();
                    conn.Close();
                }

                string rawVal = dtResults_1.Rows[0]["AVERAGE"].ToString();
                Double numValM = Math.Round(Convert.ToDouble(rawVal), 1, MidpointRounding.ToEven);
                Double numValH = Math.Round(numValM / 60, 1, MidpointRounding.ToEven);
                string finValM = Convert.ToString(numValM);
                string finValH = Convert.ToString(numValH);
                textbox_avgsession.Text = numValM + " Minutes";

                DataTable dtResults_3 = new DataTable();
                conn.Open();

                if (conn.State == ConnectionState.Open)
                {
                    OleDbCommand dbCommand = conn.CreateCommand();
                    dbCommand.CommandType = CommandType.Text;
                    dbCommand.CommandText = "SELECT Count(timetrack.[gamelink]) AS CountOfgamelink FROM timetrack WHERE gamelink = '" + gamename + "'";

                    OleDbDataReader dbReader = dbCommand.ExecuteReader();

                    if (dbReader.HasRows)
                        dtResults_3.Load(dbReader);

                    dbReader.Close();
                    conn.Close();
                }

                textbox_session.Text = dtResults_3.Rows[0]["CountOfgamelink"].ToString() + " Times";

                DataTable dtResults_2 = new DataTable();
                conn.Open();

                if (conn.State == ConnectionState.Open)
                {
                    OleDbCommand dbCommand = conn.CreateCommand();
                    dbCommand.CommandType = CommandType.Text;
                    dbCommand.CommandText = "SELECT TOP 2 timetrack.sessiontime AS sessiontime FROM timetrack WHERE gamelink = '" + gamename + "' ORDER BY sessiontime DESC;";

                    OleDbDataReader dbReader = dbCommand.ExecuteReader();

                    if (dbReader.HasRows)
                        dtResults_2.Load(dbReader);

                    dbReader.Close();
                    conn.Close();
                }
                textbox_lplay.Text = dtResults_2.Rows[0]["sessiontime"].ToString() + " Minutes";
            }
            catch (Exception ex)
            { reset(); }
        }

        public void reset()
        {
            textbox_avgsession.Text = " 0 Minutes";
            textbox_lplay.Text = " 0 Minutes";
            textbox_session.Text = "0 Times";
        }

        private void button_stats_Click(object sender, RoutedEventArgs e)
        {
            rectangle_stats.Visibility = Visibility.Hidden;
            label_stats.Visibility = Visibility.Hidden;
            textbox_playtime.Visibility = Visibility.Hidden;
            button_stats.Visibility = Visibility.Hidden;
            label_avgsession.Visibility = Visibility.Hidden;
            textbox_avgsession.Visibility = Visibility.Hidden;
            label_lplay.Visibility = Visibility.Hidden;
            textbox_lplay.Visibility = Visibility.Hidden;
            label_session.Visibility = Visibility.Hidden;
            textbox_session.Visibility = Visibility.Hidden;
        }

        private void webbrowser_defiance_Navigated(object sender, NavigationEventArgs e)
        {
            SetSilent(webbrowser_defiance, true);
        }

        public static void SetSilent(WebBrowser browser, bool silent)
        {
            if (browser == null)
                throw new ArgumentNullException("browser");

            IOleServiceProvider sp = browser.Document as IOleServiceProvider;
            if (sp != null)
            {
                Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
                Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");

                object webBrowser;
                sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser);
                if (webBrowser != null)
                {
                    webBrowser.GetType().InvokeMember("Silent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent });
                }
            }
        }


        [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IOleServiceProvider
        {
            [PreserveSig]
            int QueryService([In] ref Guid guidService, [In] ref Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject);
        }

        private void webload(object obj)
        {
            Thread.Sleep(2500);
            this.Dispatcher.Invoke((Action)(() =>
            {
                webbrowser_defiance.Visibility = Visibility.Visible;
                progressring_defiance.Visibility = Visibility.Hidden;
            }));
        }

        private void tabitem_defiance_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            webbrowser_defiance.Visibility = Visibility.Hidden;
            progressring_defiance.Visibility = Visibility.Visible;

            webbrowser_defiance.Navigated += new NavigatedEventHandler(webbrowser_defiance_Navigated);
            webbrowser_defiance.Navigate("http://forums.defiance.com/");

            Thread displaychange = new Thread(webload);
            displaychange.Start(this);
        }

        private void switch_favorite_Checked(object sender, RoutedEventArgs e)
        {
            string gamename = listbox_gamelist.SelectedItem.ToString();
            sql = @"UPDATE gamecentral SET favorite='Yes' WHERE gamename = '" + gamename + "'";
            ClassSQL.gamesupdate(sql);
        }

        private void switch_favorite_Unchecked(object sender, RoutedEventArgs e)
        {
            string gamename = listbox_gamelist.SelectedItem.ToString();
            sql = @"UPDATE gamecentral SET favorite='No' WHERE gamename = '" + gamename + "'";
            ClassSQL.gamesupdate(sql);
        }

        private void label_selection_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            textbox_search.Text = "";
            if (label_selection.Content.ToString() != "Favorite")
            {
                label_selection.Content = "Favorite";
                string sql = "SELECT * FROM gamecentral WHERE favorite='Yes' ORDER BY gamename";
                ClassSQL.gamesfill(this, sql); ClassSQL.gamesfill(this, sql);
                label_right.Visibility = Visibility.Hidden;
                label_left.Visibility = Visibility.Hidden;
            }
            else
            {
                filter1 = "IP";
                filter2 = "CO";

                label_selection.Content = "All Games";
                string sql = "SELECT * FROM gamecentral ORDER BY gamename";
                ClassSQL.gamesfill(this, sql); ClassSQL.gamesfill(this, sql);
                label_right.Visibility = Visibility.Visible;
                label_left.Visibility = Visibility.Visible;
            }
        }

        private void menuitem_selected5_Click(object sender, RoutedEventArgs e)
        {
            string gamename = listbox_gamelist.SelectedItem.ToString();
            sql = @"UPDATE gamecentral SET favorite='Yes' WHERE gamename = '" + gamename + "'";
            ClassSQL.gamesupdate(sql);
            ClassSQL.datarefresh(this);
        }
    }
}